//
// Created by yanhai on 2021/11/9.
//

#pragma once

#include <atomic>

// 参考 https://blog.csdn.net/sharemyfree/article/details/47338001

class spinlock {
public:
    spinlock() = default;
    ~spinlock() = default;
    spinlock(const spinlock &) = delete;
    spinlock &operator=(const spinlock &) = delete;

    void lock()
    {
        bool expected = false;
        while (!flag.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed))
            expected = false;
    }

    void unlock()
    {
        flag.store(false, std::memory_order_release);
    }

private:
    std::atomic<bool> flag = ATOMIC_VAR_INIT(false);
};
